﻿import sys
import os
import re
from os.path import isfile


from setuptools import setup
from setuptools import Extension
from Cython.Distutils import build_ext
from Cython.Compiler import Options
from Cython.Build import cythonize

Options.docstrings = False
Options.clear_to_none = True


config = {
    'name' : 'soui4py',
    'clear' : True
}

language = 'c'
ext = '.c'
library_dirs = []

ver = sys.version_info
print(f"Python version: {ver.major}.{ver.minor}")
is_win = sys.platform.startswith('win')
is_linux = sys.platform.startswith('linux')
is_mac = sys.platform.startswith('darwin')
x64 = (int(0).__sizeof__() == 28)  # 64-bit Python has sizeof(int) == 28
print(f"Platform: {sys.platform}, x64: {x64}")

if is_win:
    build_name = (config['name'] + '.cp' + str(ver.major) + str(ver.minor) +
        ('-win_amd64' if x64 else '-win32') + '.pyd')

    soui4_inst_path = '.\\soui5\\windows'
    if x64:
        soui4_inst_lib_path = '.\\soui5\\windows\\x64'
    else:
        soui4_inst_lib_path = '.\\soui5\\windows\\x86'
    
    print(r'!!soui4 install path is %s' % soui4_inst_path)
    library_dirs = [
        os.path.join(soui4_inst_lib_path, 'lib', 'release'),
    ]
    libraries = [
        'utilities4',
        'soui4',
        'render-gdi',
        'render-skia',
        'imgdecoder-gdip',
        'imgdecoder-stb',
        'imgdecoder-wic',
        'resprovider-zip',
        'resprovider-7zip',
        'translator',
        'taskloop',
        'log4z',
        'scriptmodule-lua',
        'sipcobject',
        'User32'
    ]
    extra_compile_args = [
        '/MT',
        '/Zc:inline',
        '/Zc:wchar_t',
        '/D_UNICODE',
        '/DUNICODE',
        '/Gd',
        '/wd4013'
    ]
    define_macros = []
    include_dirs = [
        os.path.join(soui4_inst_path, 'include', 'config'),
        os.path.join(soui4_inst_path, 'include', 'components'),
        os.path.join(soui4_inst_path, 'include', 'SOUI', 'include'),
        os.path.join(soui4_inst_path, 'include', 'utilities', 'include'),
        '.'
    ]
elif is_linux:
    build_name = (config['name'] + '.cpython' + str(ver.major) + str(ver.minor) + '-linux.pyd')
    soui4_inst_path = './soui5/linux'
    print('!!soui4 install path is %s' % soui4_inst_path)
    library_dirs = [
        os.path.join(soui4_inst_path, 'x64', 'lib', 'Release'),
    ]
    libraries = [
        'soui4',
        'swinx',
        'utilities4',
        'log4z',
        'imgdecoder-stb',
        'render-gdi',
        'render-skia',
        'resprovider-zip',
        'resprovider-7zip',
        'translator',
        'taskloop',
        'sipcobject',
        'scriptmodule-lua',
        'pthread',
        'dl',
        'm',
        'stdc++'
    ]
    extra_compile_args = [
        '-w'
    ]
    define_macros = []
    include_dirs = [
        os.path.join(soui4_inst_path, 'include', 'swinx', 'include'),
        os.path.join(soui4_inst_path, 'include', 'config'),
        os.path.join(soui4_inst_path, 'include', 'components'),
        os.path.join(soui4_inst_path, 'include', 'SOUI', 'include'),
        os.path.join(soui4_inst_path, 'include', 'utilities', 'include'),
        '.'
    ]
elif is_mac:
    build_name = (config['name'] + '.cpython' + str(ver.major) + str(ver.minor) + '-darwin.so')
    soui4_inst_path = './soui5/macos'
    print('!!soui4 install path is %s' % soui4_inst_path)
    print('!!build_name is %s' % build_name)
    library_dirs = [
        os.path.join(soui4_inst_path, 'x64', 'lib', 'Release')
    ]
    libraries = [
        'soui4',
        'swinx',
        'utilities4',
        'log4z',
        'imgdecoder-stb',
        'render-gdi',
        'render-skia',
        'resprovider-zip',
        'resprovider-7zip',
        'translator',
        'taskloop',
        'sipcobject',
        'scriptmodule-lua',
        'pthread',
        'dl',
        'm',
        'stdc++'
    ]
    extra_compile_args = [
        '-Wno-everything'
    ]
    define_macros = []
    include_dirs = [
        os.path.join(soui4_inst_path, 'include', 'swinx', 'include'),
        os.path.join(soui4_inst_path, 'include', 'config'),
        os.path.join(soui4_inst_path, 'include', 'components'),
        os.path.join(soui4_inst_path, 'include', 'SOUI', 'include'),
        os.path.join(soui4_inst_path, 'include', 'utilities', 'include'),
        '.'
    ]

ext_release = Extension(
    'soui4py',
    ['soui4py.pyx'],
    depends=['py_compat.h'],
    libraries=libraries,
    extra_compile_args=extra_compile_args,
    define_macros=define_macros,
    library_dirs=library_dirs,
    include_dirs=include_dirs,
    language=language
)

if len(sys.argv) > 1:
    ext_modules = [ext_release]

    for mod in ext_modules:
        cppfile = '%s%s' % (mod.name, ext)
        if isfile(cppfile):
            with open(cppfile) as f:
                s = f.read()
            if s == '#error Do not use this file, it is the result of a failed Cython compilation.\n':
                print('del error file')
                try:
                    os.remove(cppfile)
                except Exception:
                    pass

        if config['clear']:
            if is_win:
                name = (mod.name + '.cp' + str(ver.major) + str(ver.minor) +
                        ('-win_amd64' if x64 else '-win32') + '.pyd')
            elif is_linux:
                name = (mod.name + '.cpython' + str(ver.major) + str(ver.minor) + '-linux-gnu.so')
            elif is_mac:
                name = (mod.name + '.cpython' + str(ver.major) + str(ver.minor) + '-darwin.so')

            if isfile(name):
                try:
                    os.remove(name)
                except Exception:
                    pass

    if isfile(build_name) and config['clear']:
        for mod in ext_modules:
            if isfile(mod.name + ext):
                try:
                    os.remove(mod.name + ext)
                except Exception:
                    pass

    print('====================================build begin================================')
    setup(
        name = config['name'] + '_',
        cmdclass = {'build_ext': build_ext},
        ext_modules = cythonize(ext_modules),
        include_dirs = include_dirs
    )
    print('====================================build end================================')
